package com.wy.powerbuilder.config.ld;

import com.wy.powerbuilder.entity.ld.User;
import com.wy.powerbuilder.service.ld.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import javax.sound.midi.Soundbank;
import java.util.HashSet;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    /**
     * 执行授权逻辑
    */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权逻辑");
        //得到用户名
        String name=(String)principalCollection.getPrimaryPrincipal();
        //给当前用户赋予相应的角色
        Set<String> menus=userService.getMenu(name);
        AuthorizationInfo info=new SimpleAuthorizationInfo(menus);
        return info;
    }
    /**
     * 执行认证逻辑
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行认证逻辑");
        UsernamePasswordToken token=(UsernamePasswordToken)authenticationToken;
        User user=userService.getUser(token.getUsername());
        if(user==null){
            return null;
        }
        if(user.getU_state()==0){
            return null;
        }
        return new SimpleAuthenticationInfo(token.getUsername(),user.getU_pass(),getName());
//        String name="admin";
//        String pwd="123456";
//        if(!token.getUsername().equals(name)){
//            return null;
//        }
//        return new SimpleAuthenticationInfo("",pwd,"");
    }
}
